package com.xy6.dpdemo.book.delegate.cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * cglib用法示例。对普通类中一个方法的拦截
 * <pre>
 * 
 * </pre>
 * 
 * @author zhang
 * @since 2018-04-29
 */
public class SampleClass {

	public String test(String str){
		System.out.println("hello world");
		return "hello world";
	}
	
	public static void main(String[] args) {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(SampleClass.class);
		enhancer.setCallback(new MethodInterceptor(){
			@Override
			public Object intercept(Object obj, Method m, Object[] args, MethodProxy proxy) throws Throwable {
				System.out.println("before run");
				Object result = proxy.invokeSuper(obj, args);
				System.out.println("after run");
				return result;
			}
		});
		SampleClass sample = (SampleClass)enhancer.create();
		sample.test("abc");
	}

}
